<!-- components/PriceRuleEditor.vue -->
<template>
  <view class="rule-editor">
    <scroll-view scroll-y class="editor-content">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="label">价格类型</text>
          <picker :value="rule.price_type" :range="priceTypes" @change="changePriceType">
            <view class="picker">
              {{priceTypes[rule.price_type]}}
              <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label">优先级</text>
          <input type="number" v-model="rule.priority" class="input" placeholder="数值越大优先级越高" />
        </view>
        
        <view class="form-item">
          <text class="label">状态</text>
          <switch :checked="rule.status" @change="rule.status = $event.detail.value" color="#FF7F00" />
        </view>
      </view>
      
      <view class="form-section">
        <text class="section-title">适用范围</text>
        
        <view class="form-item">
          <text class="label">站点</text>
          <picker :value="depotIndex" :range="depots" range-key="name" @change="changeDepot">
            <view class="picker">
              {{rule.scope.depot_id ? selectedDepot.name : '全部站点'}}
              <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view v-if="rule.price_type !== 3" class="form-item">
          <text class="label">箱型</text>
          <picker :value="rule.scope.size_type" :range="sizeTypes" @change="changeSizeType">
            <view class="picker">
              {{rule.scope.size_type !== undefined ? sizeTypes[rule.scope.size_type] : '全部箱型'}}
              <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view v-if="rule.price_type === 3" class="form-item">
          <text class="label">会员等级</text>
          <picker :value="rule.scope.member_level" :range="memberLevels" @change="changeMemberLevel">
            <view class="picker">
              {{memberLevels[rule.scope.member_level]}}
              <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
      </view>
      
      <view class="form-section">
        <text class="section-title">租期设置</text>
        
        <view class="form-item">
          <text class="label">租期单位</text>
          <picker :value="rule.duration.unit" :range="durationUnits" @change="changeDurationUnit">
            <view class="picker">
              {{durationUnits[rule.duration.unit]}}
              <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label">租期数值</text>
          <input type="number" v-model="rule.duration.value" class="input" placeholder="例如: 1" />
        </view>
        
        <view class="form-row">
          <view class="form-item half">
            <text class="label">最短租期</text>
            <input type="number" v-model="rule.duration.min_duration" class="input" placeholder="可选" />
          </view>
          
          <view class="form-item half">
            <text class="label">最长租期</text>
            <input type="number" v-model="rule.duration.max_duration" class="input" placeholder="可选" />
          </view>
        </view>
      </view>
      
      <view class="form-section">
        <text class="section-title">价格设置</text>
        
        <view class="form-item">
          <text class="label">基础价格(元)</text>
          <input type="number" v-model="rule.price.base_price" class="input" placeholder="0.00" />
        </view>
        
        <view class="form-item">
          <text class="label">优惠类型</text>
          <picker :value="rule.price.discount_type" :range="discountTypes" @change="changeDiscountType">
            <view class="picker">
              {{discountTypes[rule.price.discount_type]}}
              <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label">优惠值</text>
          <input type="number" v-model="rule.price.discount_value" class="input" 
            :placeholder="rule.price.discount_type === 0 ? '例如: 0.9 (9折)' : '例如: 10 (减10元)'" />
        </view>
        
        <view class="form-item">
          <text class="label">最终价格(元)</text>
          <input type="number" v-model="rule.price.final_price" class="input" placeholder="0.00" />
        </view>
      </view>
      
      <view v-if="rule.price_type === 1" class="form-section">
        <text class="section-title">续期规则</text>
        
        <view class="form-item">
          <text class="label">允许续期</text>
          <switch :checked="rule.renewal_rules.allow_renewal" 
            @change="rule.renewal_rules.allow_renewal = $event.detail.value" 
            color="#FF7F00" />
        </view>
        
        <view v-if="rule.renewal_rules.allow_renewal" class="form-item">
          <text class="label">续期价格(元)</text>
          <input type="number" v-model="rule.renewal_rules.renewal_price" class="input" placeholder="0.00" />
        </view>
        
        <view v-if="rule.renewal_rules.allow_renewal" class="form-item">
          <text class="label">续期单位</text>
          <picker :value="rule.renewal_rules.renewal_unit" :range="durationUnits" @change="changeRenewalUnit">
            <view class="picker">
              {{durationUnits[rule.renewal_rules.renewal_unit]}}
              <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view v-if="rule.renewal_rules.allow_renewal" class="form-item">
          <text class="label">最大续期次数</text>
          <input type="number" v-model="rule.renewal_rules.max_renewal" class="input" placeholder="例如: 3" />
        </view>
      </view>
      
      <view v-if="rule.price_type === 2" class="form-section">
        <text class="section-title">超时规则</text>
        
        <view v-for="(overtime, index) in rule.overtime_rules" :key="index" class="overtime-rule">
          <view class="rule-header">
            <text>规则 {{index + 1}}</text>
            <uni-icons type="close" size="18" color="#F44336" @click="removeOvertimeRule(index)"></uni-icons>
          </view>
          
          <view class="form-item">
            <text class="label">超时阈值(分钟)</text>
            <input type="number" v-model="overtime.threshold" class="input" placeholder="例如: 60" />
          </view>
          
          <view class="form-item">
            <text class="label">罚金类型</text>
            <picker :value="overtime.penalty_type" :range="penaltyTypes" @change="changePenaltyType($event, index)">
              <view class="picker">
                {{penaltyTypes[overtime.penalty_type]}}
                <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="label">罚金值</text>
            <input type="number" v-model="overtime.penalty_value" class="input" 
              :placeholder="overtime.penalty_type === 0 ? '固定金额' : '倍数或费率'" />
          </view>
          
          <view class="form-item">
            <text class="label">最高罚金(元)</text>
            <input type="number" v-model="overtime.max_penalty" class="input" placeholder="可选" />
          </view>
        </view>
        
        <button class="add-rule-btn" @click="addOvertimeRule">+ 添加超时规则</button>
      </view>
      
      <view class="form-section">
        <text class="section-title">生效时间</text>
        
        <view class="form-row">
          <view class="form-item half">
            <text class="label">开始时间</text>
            <picker mode="date" :value="effectiveDate" @change="changeEffectiveDate">
              <view class="picker">
                {{effectiveDate || '选择日期'}}
                <uni-icons type="calendar" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </view>
          
          <view class="form-item half">
            <text class="label">结束时间</text>
            <picker mode="date" :value="expireDate" @change="changeExpireDate">
              <view class="picker">
                {{expireDate || '选择日期'}}
                <uni-icons type="calendar" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <view class="action-bar">
      <button class="cancel-btn" @click="$emit('cancel')">取消</button>
      <button class="save-btn" @click="$emit('save', rule)">保存规则</button>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    rule: {
      type: Object,
      required: true
    },
    depots: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      priceTypes: ['基础价格', '续期价格', '超时价格', '会员价格', '套餐价格', '节假日价格'],
      sizeTypes: ['小箱型', '中箱型', '大箱型'],
      durationUnits: ['小时', '天', '周', '月'],
      memberLevels: ['普通会员', '白银会员', '黄金会员', '钻石会员'],
      discountTypes: ['折扣', '减价'],
      penaltyTypes: ['固定金额', '基础价格倍数', '额外费率']
    }
  },
  computed: {
    depotIndex() {
      if (!this.rule.scope.depot_id) return -1
      return this.depots.findIndex(d => d._id === this.rule.scope.depot_id)
    },
    selectedDepot() {
      return this.depots.find(d => d._id === this.rule.scope.depot_id) || {}
    },
    effectiveDate() {
      return this.formatDate(this.rule.effective_date)
    },
    expireDate() {
      return this.formatDate(this.rule.expire_date)
    }
  },
  created() {
    // 初始化规则
    if (!this.rule.scope) this.rule.scope = {}
    if (!this.rule.duration) this.rule.duration = { unit: 0, value: 1 }
    if (!this.rule.price) this.rule.price = { base_price: 0, discount_type: 0, discount_value: 1, final_price: 0 }
    if (this.rule.price_type === 1 && !this.rule.renewal_rules) {
      this.rule.renewal_rules = {
        allow_renewal: true,
        renewal_price: 0,
        renewal_unit: 0,
        max_renewal: null
      }
    }
    if (this.rule.price_type === 2 && !this.rule.overtime_rules) {
      this.rule.overtime_rules = []
    }
  },
  methods: {
    formatDate(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    },
    
    changePriceType(e) {
      const type = parseInt(e.detail.value)
      this.rule.price_type = type
      
      // 重置相关字段
      if (type === 3) {
        // 会员价格
        this.rule.scope.size_type = undefined
        this.rule.scope.member_level = 0
      } else {
        this.rule.scope.member_level = undefined
      }
      
      if (type === 1) {
        // 续期价格
        if (!this.rule.renewal_rules) {
          this.rule.renewal_rules = {
            allow_renewal: true,
            renewal_price: 0,
            renewal_unit: 0,
            max_renewal: null
          }
        }
      }
      
      if (type === 2) {
        // 超时价格
        if (!this.rule.overtime_rules || this.rule.overtime_rules.length === 0) {
          this.rule.overtime_rules = [{
            threshold: 60,
            penalty_type: 0,
            penalty_value: 5,
            max_penalty: null
          }]
        }
      }
    },
    
    changeDepot(e) {
      const index = e.detail.value
      if (index >= 0) {
        this.rule.scope.depot_id = this.depots[index]._id
      } else {
        this.rule.scope.depot_id = null
      }
    },
    
    changeSizeType(e) {
      const value = e.detail.value
      this.rule.scope.size_type = value !== '' ? parseInt(value) : undefined
    },
    
    changeMemberLevel(e) {
      this.rule.scope.member_level = parseInt(e.detail.value)
    },
    
    changeDurationUnit(e) {
      this.rule.duration.unit = parseInt(e.detail.value)
    },
    
    changeDiscountType(e) {
      this.rule.price.discount_type = parseInt(e.detail.value)
    },
    
    changeRenewalUnit(e) {
      this.rule.renewal_rules.renewal_unit = parseInt(e.detail.value)
    },
    
    changePenaltyType(e, index) {
      this.rule.overtime_rules[index].penalty_type = parseInt(e.detail.value)
    },
    
    addOvertimeRule() {
      this.rule.overtime_rules.push({
        threshold: 60,
        penalty_type: 0,
        penalty_value: 5,
        max_penalty: null
      })
    },
    
    removeOvertimeRule(index) {
      this.rule.overtime_rules.splice(index, 1)
    },
    
    changeEffectiveDate(e) {
      this.rule.effective_date = new Date(e.detail.value).getTime()
    },
    
    changeExpireDate(e) {
      this.rule.expire_date = new Date(e.detail.value).getTime()
    }
  }
}
</script>

<style lang="scss">
.rule-editor {
  background: #fff;
  border-radius: 20px 20px 0 0;
  padding: 20px 15px 100px;
  max-height: 80vh;
}

.editor-content {
  max-height: 65vh;
}

.form-section {
  margin-bottom: 20px;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 12px;
    display: block;
    color: #FF7F00;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.form-item {
  margin-bottom: 15px;
  
  .label {
    display: block;
    font-size: 14px;
    color: #666;
    margin-bottom: 5px;
  }
  
  .picker {
    background: #f5f5f5;
    border-radius: 8px;
    padding: 10px 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .input {
    background: #f5f5f5;
    border-radius: 8px;
    padding: 10px 15px;
    height: 40px;
    font-size: 14px;
  }
}

.form-row {
  display: flex;
  gap: 15px;
  
  .form-item {
    flex: 1;
    margin-bottom: 0;
    
    &.half {
      flex: 0.5;
    }
  }
}

.overtime-rule {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 15px;
  
  .rule-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
}

.add-rule-btn {
  background: #FFF5EB;
  color: #FF7F00;
  border-radius: 20px;
  font-size: 14px;
  height: 36px;
  line-height: 36px;
  margin-top: 10px;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 15px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  
  button {
    flex: 1;
    height: 44px;
    border-radius: 22px;
    font-size: 16px;
    
    &.cancel-btn {
      background: #f5f5f5;
      color: #333;
      margin-right: 15px;
    }
    
    &.save-btn {
      background: #FF7F00;
      color: #fff;
    }
  }
}
</style>